
angular.module('theApp.common', [])

.run(function(root, $rootScope, $location, $route, $templateCache) {
    $rootScope.signOut = function() {
        root.unauth();
        $location.path('/home');
        $route.reload();
    };
        
    $rootScope.$on('$viewContentLoaded', function() {
        $templateCache.removeAll();
    });
    
    $rootScope.reloaded = true;
})

.value('root', (new Firebase('https://ssw-ng1-1.firebaseio.com')))

.service('A', function() {

    return {
   
        send_email: function($http, $scope, to, from, subject, text) {
            
            var srv = "php/server.php";
            var x = {'op': 'email', 'data': {"to": to, "from": from, "subject": subject, "text": text}};            
            $http.post(srv, {'payload': x}).success(function(data, status, headers, config) {      
                 $scope.response = JSON.stringify(data);
            }).error(function(data, status, headers, config) {
            });
        },
        
        get_user_data_from_provider: function(root, $rootScope, $location, $route, authData) {
            var uid = authData.uid;
            var uRef = root.child('users').child(uid);
            uRef.once('value', function(snap) {
                var prov = authData.provider;
                var data = snap.val();
                var luser = authData;
                if (data === null) {
                    luser.email = '-- email --';
                    luser.permission = 'User';
                    luser.phone1 = '555-555-5555';
                    luser.phone2 = '555-555-5555';
                    luser.phone3 = '555-555-5555';
                    luser.phone4 = '555-555-5555';
                    luser.lastname = '-- last name --';
                    luser.firstname = '-- last name --';
                    uRef.set(luser);                                    
                } else {
                    luser.email = data.email;
                    luser.permission = data.permission;
                    luser.phone1 = data.phone1;
                    luser.phone2 = data.phone2;
                    luser.phone3 = data.phone3;
                    luser.phone4 = data.phone4;                                    
                    luser.lastname = data.lastname;
                    luser.firstname = data.firstname;
                }
                
                if (prov === 'facebook') {
                    luser.email = authData[prov].email;
                    luser.lastname = authData.facebook.cachedUserProfile.last_name;
                    luser.firstname = authData.facebook.cachedUserProfile.first_name;
                }
                else if (prov === 'google') {
                    luser.email = authData[prov].email;
                    luser.lastname = authData.google.cachedUserProfile.family_name;
                    luser.firstname = authData.google.cachedUserProfile.given_name;                    
                }
                else if (prov === 'twitter') {         
                    luser.lastname = authData.twitter.cachedUserProfile.name + ' --- ';
                    luser.firstname = authData.twitter.cachedUserProfile.name + ' --- ';
                }
                else if (prov === 'password') {         
                    luser.email = authData[prov].email;
                }

                uRef.update(luser);                                    
                            
                $rootScope.luser = luser;
                
                $location.path('/home');
                $route.reload();
            });
            
            $location.path('/home');
        }
    };
})

.controller('errorController', function($scope, $rootScope, $routeParams) {
    var id = $routeParams.id;
    if (id === undefined) {
        $scope.msg = $rootScope.errors[id];
        return;
    }
    $scope.msg = "Unknown error";
 })
    
.controller('authController', function(root, $rootScope, $location, $route, A) {
    root.onAuth(function(authData) {
        if (authData) {
            console.log("User ID: " + authData.uid + ", Provider: " + authData.provider);
            A.get_user_data_from_provider(root, $rootScope,  $location, $route, authData);
        } else {
            $rootScope.luser = null;
            console.log('No user');
            if ($rootScope.reloaded) {
                $location.path('/home');
            } else {
                $location.path('/wait');
            }
        }
    });
 })
    
.controller('loginController', function(root, $scope, $location) {
        
    $scope.credentialsAreSound = function(register) {
        if ($scope.email === undefined) {
            return false;
        }
        if ($scope.password === undefined) {
            return false;
        }
        if ($scope.password.length < 1) {
            return false;
        }
        if (register) {
            if ($scope.password2 === undefined) {
                return false;
            }
            if ($scope.password2.length < 1) {
                return false;
            }
        }
        return true;
    },
    
    $scope.signInSimple = function(register) {
        root.authWithPassword({
            email: $scope.email,
            password: $scope.password,
            rembember: 'never'
        }, 
        function(error, authData) {
            if (error === null) {
                console.log("User ID: " + authData.uid + ", Provider: " + authData.provider);
            } else {
                switch (error.code) {
                    case "INVALID_USER":
                        if (register === false) {
                            alert('Invalid credentials.');
                            break;
                        }
                        if ($scope.password !== $scope.password2) {
                            alert('Passwords do not match.');
                            break;
                        } 
                        var yn = prompt("Do you want to create a new user account for " + $scope.email + "? Type YES if you do", "NO");
                        if (yn === "YES") {
                            alert('OK');                            
                            root.createUser({
                                email: $scope.email,
                                password: $scope.password
                            }, 
                            function(error) {
                                if (error === null) {
                                    console.log("User " + $scope.email + " created successfully");
                                    $scope.signInSimple();
                                } else {
                                    console.log("Error creating user:", error);
                                }
                            });
                        } else {
                            alert('Too bad');                            
                        }
                        break;
                    case "INVALID_PASSWORD":
                        console.log("Error authenticating user:", error);
                        alert('Invalid credentials');
                        break;
                    default:
                        console.log("Error authenticating user:", error);
                        alert('Invalid credentials');
                }
            }
        });
    };

    $scope.signInOAuth = function(provider) {
    
        var scope = "email";
        var options = {};
        options.remember = 'never';
        if (provider === 'facebook') {
            scope = scope + ',public_profile';
        }
        if (provider === 'google') {
            scope = scope + ',profile';
        }
        options.scope = scope;
        root.authWithOAuthRedirect(provider, 
            function(error, authData) { 
                if (error === null) {
                    console.log("User ID: " + authData.uid + ", Provider: " + authData.provider);
                } else {
                    console.log("Error authenticating user:", error);
                    alert('Invalid credentials');
                }
            },
            options
        );
        
        $location.path('/wait');
    };
  
})

;
